<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      :search.sync="searchForm"
      :data="tableData"
      :page.sync="page"
      :table-loading="tableLoading"
      :option="tableOption"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      @on-load="getList"
      @search-change="searchChange"
      @search-reset="searchReset"
      @row-update="handleUpdate"
      @row-save="handleSave"
    >
      <!-- <template #userChoiceFlag="scope">
        <el-switch
          :value="scope.row.userChoiceFlag"
          inactive-value="1"
          active-value="0"
        />
      </template> -->
      <template slot="menuLeft">
        <el-button
          type="primary"
          size="small"
          @click="insertLabel"
        >
          新增
        </el-button>
      </template>
      <template v-slot:menu="{ row }">
        <el-button
          size="small"
          type="text"
          @click="editLabel(row)"
        >
          编辑
        </el-button>
        <el-button
          size="small"
          type="text"
          @click="deleteLabel(row)"
        >
          删除
        </el-button>
        <el-button
          size="small"
          type="text"
          @click="tagManage(row)"
        >
          标签管理
        </el-button>
        <!-- <el-button
          size="small"
          type="text"
          @click="addChildrenChange(row)"
        >
          新增标签
        </el-button> -->
        <!-- <el-button
          v-if="row.parentId === '0'"
          size="small"
          type="text"
          @click="tagManage(row)"
        >
          标签管理
        </el-button>
        <el-button
          v-if="row.parentId !== '0'"
          size="small"
          type="text"
          @click="lookLabelUser(row)"
        >
          标签用户
        </el-button> -->
      </template>
    </avue-crud>
    <labelUser
      v-model="visible"
      :node-id="nodeId"
    ></labelUser>
    <tagName
      :id="id"
      v-model="tagVisible"
    ></tagName>
    <add-dialog
      :id="id"
      v-model="addVisible"
      :action="action"
      @refresh="getList"
    ></add-dialog>
  </basic-container>
</template>

<script>
import { tableOption } from '@/const/crud/customer/labelMng';
import addDialog from './components/addDialog.vue';
import { addObj, putObj, getObj } from '@/api/app/labelMng';
import {
  fetchLabelList,
  updateLabel,
  deleteLabel,
} from '@/api/app/custom-label';
import crudMixins from '@/mixins/crud';
import { IS_HOT, LABEL_STATUS } from '@/const/type';
import labelUser from './components/labelUser.vue';
import tagName from './components/tagName.vue';
export default {
  name: 'classifyMng',
  components: { labelUser, tagName, addDialog },
  mixins: [crudMixins],
  data() {
    return {
      form: {},
      id: '',
      IS_HOT: Object.freeze(IS_HOT),
      LABEL_STATUS: LABEL_STATUS,
      parentId: '0',
      firstData: [],
      visible: false,
      tagVisible: false,
      maps: new Map(),
      parentName: '',
      nodeId: null,
      action: 'add',
      addVisible: false,
    };
  },
  computed: {
    tableOption() {
      return tableOption(this.form.parentId);
    },
  },
  methods: {
    //编辑
    editLabel(row) {
      this.id = row.id;
      this.action = 'edit';
      this.addVisible = true;
    },
    //标签管理
    tagManage(row) {
      this.id = row.id;
      this.tagVisible = true;
    },
    //新增
    insertLabel() {
      this.action = 'add';
      this.addVisible = true;
    },
    //用户自选
    handleChoiceChange(e, row) {
      const tip = e === '1' ? '是否关闭用户自选？' : '是否开启用户自选';
      const status = e === '1' ? LABEL_STATUS.CLOSE : LABEL_STATUS.OPEN;
      this.$confirm(`${tip}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const params = {
          id: row.id,
          userChoiceFlag: status,
        };
        updateLabel(params).then(() => {
          this.getList();
          this.$message.success(e === '1' ? '已关闭' : '已开启');
        });
      });
    },
    updateTable(key) {
      // 在删除或者添加操作成功之后，调用此函数
      if (this.maps.get(key)) {
        const { node, child, resolve } = this.maps.get(key);
        // 将对应节点下的数据清空，从而实现数据的重新加载
        this.$set(
          this.$refs.crud.$refs.table.store.states.lazyTreeNodeMap,
          key,
          []
        );
        this.treeLoad(node, child, resolve);
      }
    },
    // 获取列表
    getList(page, refresh) {
      if (refresh) {
        this.page.current = 1;
        this.page.currentPage = 1;
      }
      this.tableLoading = true;
      fetchLabelList(
        Object.assign(
          {
            current: this.page.currentPage,
            size: this.page.pageSize,
            type: this.searchForm.userChoiceFlag,
          },
          this.searchForm
        )
      )
        .then((response) => {
          console.log('response', response);
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // async getList() {
    //   try {
    //     this.tableLoading = true;
    //     const { data } = await fetchLabelList({
    //       ...this.searchForm,
    //     });
    //     this.tableData = data.data.records;
    //     this.tableData.forEach((el) => {
    //       // el.parentId = '0';
    //       el.hasChildren = true;
    //       el.userSelect = '1'; // todo5
    //       el.tagType = '1'; // todo5
    //     });
    //     this.tableLoading = false;
    //   } catch (error) {
    //     this.tableLoading = false;
    //     throw new Error(error);
    //   }
    // },
    // 编辑
    async handleUpdate(row, index, done, loading) {
      const params = { ...row };
      params.name = row.parentId === '0' ? row.name : row.subName;
      try {
        await putObj(params);
        done();
        this.getList();
        this.updateTable(row.parentId);
      } catch (error) {
        loading();
        throw new Error(error);
      }
    },
    // 保存
    async handleSave(row, done, loading) {
      const params = { ...row };
      params.name = row.parentId === '0' ? row.name : row.subName;
      try {
        await addObj(params);
        done();
        this.getList();
        this.updateTable(row.parentId);
      } catch (error) {
        loading();
        throw new Error(error);
      }
    },
    // 删除
    deleteLabel(row) {
      this.$confirm(
        '删除后将不可恢复，并清除用户的标签数据，确认删除该标签吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        await deleteLabel(row.id);
        this.$message.success('删除成功');
        this.getList();
        this.updateTable(row.parentId);
      });
    },
    addChildrenChange(row) {
      this.parentId = row.id;
      this.parentName = row.name;
      this.$refs.crud.rowAdd();
    },

    lookLabelUser(row) {
      this.nodeId = row.id;
      this.visible = true;
    },
    // 打开前的拦截
    async beforeOpen(done, type) {
      if (type !== 'add') {
        const res = await getObj(this.form.id);
        this.form = { ...res.data.data };
        if (this.form.parentId !== '0') {
          this.form.subName = this.form.name;
          this.form.name = this.tableData.find(
            (el) => el.id === this.form.parentId
          ).name;
        }
      } else {
        this.form.parentId = this.parentId;
        this.form.name = this.parentName;
      }
      done();
    },
    beforeClose(done) {
      this.parentId = '0';
      this.parentName = '';
      done();
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-classify {
  .el-collapse-item__header {
    margin-bottom: 0;
  }
  .avue-upload.avue-upload--list {
    position: absolute;
    width: 100%;
    text-align: left;
  }
  .avue-upload__avatar {
    width: 100px;
    height: 100px;
    line-height: 100px !important;
  }
}
</style>
